# -*- coding = utf-8 -*-
# @Time : 2024/6/9 18:15
# @Author : 0505200213石浪
# @File : square.py
# @Software : PyCharm

from flask import request, jsonify, render_template, redirect, url_for, session
from . import bp
from db_operations import Database
import os

db = Database()
dynamic = 'static/assets/img/dynamic'  # 广场动态图片存放地址
os.makedirs(dynamic, exist_ok=True)  # 创建文件夹


# 广场页面
@bp.route('/squire/<username>')
def squire(username):
    sql = 'SELECT * FROM movieFriends.squire ORDER BY id DESC'
    squire = db.execute(sql)
    return render_template('squire.html', squire=squire, username=username)


# 广场动态id是否有回复按钮
@bp.route('/get_is_squire_reply', methods=['GET'])
def get_is_squire_reply():
    sql = "SELECT squire_id FROM movieFriends.square_replies"
    squire_id = db.execute(sql)
    return jsonify(squire_id)


# 广场获取回复的内容
@bp.route('/get_squire_reply', methods=['GET'])
def get_squire_reply():
    comment_id = request.args.get('commentId')
    sql = "SELECT * FROM movieFriends.square_replies WHERE squire_id = %s"
    squire_reply = db.execute(sql, (comment_id,))
    dict_list = []
    for comment in squire_reply:
        dict_list.append({'id': comment[0], 'user_comment_id': comment[1], 'user_id': comment[2], 'content': comment[3],
                          'username': comment[4], 'time': comment[5], 'avatar': comment[6]})
    return jsonify(dict_list)


# 广场回复逻辑处理逻辑
@bp.route('/submit_reply_squire/<username>', methods=['POST'])
def submit_reply_squire(username):
    data = request.json
    squire_id = data['user_comment_id']
    content = data['content']
    sql = "INSERT INTO movieFriends.square_replies (squire_id, user_id, content, user_name, avatar) VALUES (%s, %s, " \
          "%s, %s, %s) "
    params = (squire_id, session[username]['id'], content, username, session[username]['avatar'])
    db.execute(sql, params)
    return jsonify({"message": "广场回复成功"}), 200


# 广场发布编辑页面
@bp.route('/publish_squire/<username>')
def publish_squire(username):
    return render_template('Publish updates.html', username=username)


# 广场发布动态逻辑处理
@bp.route('/submit_squire/<username>', methods=['POST'])
def submit_squire(username):
    if request.method == 'POST':
        content = request.form['content']
        photo = request.files['photo']
        if photo:
            photo_path = os.path.join(dynamic, photo.filename)
            photo.save(photo_path)
            sava_photo_path = "../" + photo_path
        else:
            sava_photo_path = ''
        sql_edit = "INSERT INTO movieFriends.squire(username, photo, content, avatar) VALUES (%s, %s, %s, %s)"
        params = (username, sava_photo_path, content, session[username]['avatar'])
        db.execute(sql_edit, params)
        return redirect(url_for('main.squire', username=username))
